package com.symaster.common.connect.v3.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author yinmiao
 * @version 2024/1/1
 */
public class TcpClient {

    private final String address;
    private final int port;
    private boolean run = false;

    public TcpClient(String address, int port) {
        this.address = address;
        this.port = port;
    }

    public void start() throws IOException {
        run = true;

        Socket socket = new Socket(address, port);

        InputStream inputStream = socket.getInputStream();

        byte[] cache = new byte[8];
        while (run) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            do {
                int read = inputStream.read(cache);

                if (read > 0) {
                    byteArrayOutputStream.write(cache, 0, read);
                }
            } while (inputStream.available() > 0);

            System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        TcpClient tcpClient = new TcpClient("127.0.0.1", 6555);
        tcpClient.start();
    }
}
